import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:geolocator/geolocator.dart';
import 'package:libflutter/logger/logger.dart';

class TestLocationWidget extends StatefulWidget {
  const TestLocationWidget({super.key});

  @override
  State<TestLocationWidget> createState() {
    return _TestLocationState();
  }
}

class _TestLocationState extends State<TestLocationWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("定位"),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(">>>>>> 类似Android的相对布局"),
            TextButton(onPressed: () async {
              // 申请权限
               final serviceEnabled =  await Geolocator.isLocationServiceEnabled();
              if (!serviceEnabled) {
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                  content: Text('Location service disabled'),
                ));
                return ;
              }
              var permission = await Geolocator.checkPermission();
              if (permission == LocationPermission.denied) {
                permission = await Geolocator.requestPermission();
                if (permission == LocationPermission.denied) {
                  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                    content: Text('Permission denied'),
                  ));
                  return Future.error('Location permissions are denied');
                }
              }

              if (permission == LocationPermission.deniedForever) {
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                  content: Text('Location permissions are permanently denied'),
                ));
                return ;
              }

              final position = await Geolocator.getCurrentPosition();

              Logcat.E("Get position ${position}");
              // 进行定位
            }, child: Text("请求位置"))
          ],
        ),
      ),
    );
  }
}
